package com.yuushya.utils.controller

import com.yuushya.utils.FileUtils
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.LinkedList
import java.util.concurrent.LinkedBlockingQueue
import kotlin.io.path.isDirectory

@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
@Component
class Dustbin {
    companion object{
        private val dustbin: LinkedBlockingQueue<Path> = LinkedBlockingQueue()
        fun throwJunk(path: Path){ dustbin.put(path) }
    }

    @Async
    @Scheduled(fixedDelay = 1000) //间隔10秒
    @Throws(InterruptedException::class)
    fun emptyJunk() {
        val queue = LinkedList<Path>()
        while(!dustbin.isEmpty()){
            val junk = dustbin.take()
            println("now delete $junk")
            try{
                if(junk.isDirectory())
                    FileUtils.deleteAll(junk)
                else
                    Files.deleteIfExists(junk)
            }
            catch (e:IOException){
                queue.push(junk)
            }
        }
        while(!queue.isEmpty()){ throwJunk(queue.pop()) }
        Thread.sleep(10000)
    }

}